package net.vinote.smart.platform.timer;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import net.vinote.smart.platform.comm.DateFunction;
import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.database.bo.DBQuery;
import net.vinote.smart.platform.module.log.RunLogger;

import org.apache.commons.lang.math.NumberUtils;

/**
 * 系统定时任务监控
 * 
 * @author Seer
 * @version SystemTaskMonitorTask.java, v 0.1 2015年3月5日 下午2:48:41 Seer Exp.
 */
public class SystemTaskMonitorTask extends AbstractSmartTimerTask {

	@Override
	public void run() {
		DBManager bm = new DBManager("timer_task");
		try {
			DBQuery query = bm.createQuery(new String[] { "id", "title",
					"triggerClass", "startTime", "finishTime", "period",
					"periodType" },
					"(startTime is null or startTime='' or startTime<?) "
							+ " and autostart=? and isinuse=? ");

			query.setParamVal(
					DateFunction.getDate(new Date(System.currentTimeMillis()
							+ period), DateFunction.DEFAULT_FORMAT),
					PlatformConst.YES, PlatformConst.YES);
			List<BizObject> list = query.getResultList();
			if (list == null || list.size() == 0) {
				return;
			}
			for (BizObject biz : list) {
				TimerTaskStatus status = TimerManager.getInstance()
						.getTaskStatus(biz.getAttribute("id"));
				// 自行运行结束的不再启动
				if (status == TimerTaskStatus.CANCELLED
						|| status == TimerTaskStatus.EXECUTED) {
					continue;
				}
				TimerManager.getInstance().schedule(
						biz.getAttribute("id"),
						DateFunction.getTime(biz.getAttribute("startTime")),
						DateFunction.getTime(biz.getAttribute("finishTime")),
						TimeUnit.valueOf(biz.getAttribute("periodType"))
								.toMillis(
										NumberUtils.toLong(biz
												.getAttribute("period"))),
						biz.getAttribute("triggerClass"));
				if (status == null) {
					RunLogger.getLogger().log(
							Level.SEVERE,
							"schedule task[id:" + biz.getAttribute("id")
									+ " ,title:" + biz.getAttribute("title"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
